axios.defaults.baseURL = 'http://127.0.0.1:8888'

// 拦截请求，添加请求头
axios.interceptors.request.use(config => {
  config.headers.Authorization =  window.localStorage.getItem('token')
  // 在最后必须 return config
  return config
})

axios.interceptors.response.use(config => config,
  err => {
    // console.dir(err)
    if (err.response.status === 404) {
      window.alert('无法请求到' + err.response.config.baseURL + err.response.data.path)
    } else if (err.response.status === 505) {
      window.alert(err.response.message)
      window.location.href = "login.html"
    }
  }
)


const callbackhandler = (promise, callback) => {
    promise.then(
      response => {
      // console.log(response)
        if (response.data.status === 200) {
          callback(response.data)
        } else {
          window.alert(response.data.message)
        }
      }
    ).catch(() => {
    }).finally(() => {
    })
  }
  
let $axios =  {
    get (url, callback, params = {}) {
        callbackhandler(axios.get(url, { params: params }), callback)
    },
    post (url, callback, data = {}) {
        callbackhandler(axios.post(url, data), callback)
    },
    put (url, callback, data = {}) {
        callbackhandler(axios.put(url, data), callback)
    },
    del (url, callback, params = {}) {
        if (window.confirm('确定要删除数据吗?')){
            callbackhandler(axios.delete(url, { params: params }), callback)
        }
    },
    // 讲原生的axios 暴露 ，自定义使用
    http: axios
}
